/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.renren.modules.category.entity.*;
import io.renren.modules.category.service.TBrandService;
import io.renren.modules.category.service.TCategoryService;
import io.renren.modules.category.service.TConsumerService;
import io.renren.modules.category.service.TInitialService;
import org.apache.commons.collections4.CollectionUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 区分：男士女士数据
 * 执行顺序
 * 1.把业务王冉提供的品牌Excel 导入到
 * 2.运行 ExcelTest.testImportExcel() 两次，
 * 第一次 consumerId=101L，D:\\devtools\\work\\奢侈品/brand_miss.xlsx
 * 第二次consumerId=102L,D:\devtools\work\奢侈品/brand_man.xlsx;
 * 目的是把 excel数据导入到 t_brand 表中
 * 3.运行CategoryTest811.buildJson() 生成的 json
 * 4.第三步的json 放到ducc开关中
 *
 * 测试：
 * 运行CategoryTest811.testParseJson consumerId传参101或102
 * brandCategoryJson 值为第三步生成的json
 *
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class CategoryTest811 {
    @Autowired
    private TConsumerService consumerService;
    @Autowired
    private TBrandService brandService;
    @Autowired
    private TInitialService initialService;
    @Autowired
    private TCategoryService categoryService;


    /**
     * 构建Json 全部品牌和 商品品类
     */
    @Test
    public void buildJson(){
        String brandJson = buildBrandJson();
        System.out.println("");
        System.out.println(brandJson);
    }

    /**
     * 解析Json 数据
     * 入参：
     * consumerId:101
     * collection: 1:只看收藏
     */
    @Test
    public void testParseJson(){
        Long consumerId=102L;
        Boolean collection=true;
        String brandCategoryJson="[{\"id\":101,\"name\":\"女士\",\"sort\":1,\"initialList\":[{\"name\":\"热门品牌\",\"consumerId\":101,\"sort\":0,\"brandList\":[{\"id\":1005,\"name\":\"GUCCI\",\"initialId\":10006,\"initialCode\":\"HOT\",\"consumerId\":101,\"sort\":1},{\"id\":1006,\"name\":\"CHANNEL\",\"initialId\":10006,\"initialCode\":\"HOT\",\"consumerId\":101,\"sort\":1}]},{\"name\":\"A\",\"consumerId\":101,\"sort\":1,\"brandList\":[{\"id\":1008,\"name\":\"AEG\",\"initialId\":10007,\"initialCode\":\"A\",\"consumerId\":101,\"sort\":1},{\"id\":1007,\"name\":\"Acne Studios\",\"initialId\":10007,\"initialCode\":\"A\",\"consumerId\":101,\"sort\":2}]}]},{\"id\":102,\"name\":\"男士\",\"sort\":2,\"initialList\":[{\"name\":\"热门品牌\",\"consumerId\":102,\"sort\":0,\"brandList\":[{\"id\":1009,\"name\":\"GUCCI\",\"initialId\":10016,\"initialCode\":\"G\",\"consumerId\":102,\"sort\":1}]},{\"name\":\"A\",\"consumerId\":102,\"sort\":1,\"brandList\":[{\"id\":1014,\"name\":\"AEG\",\"initialId\":10017,\"initialCode\":\"A\",\"consumerId\":102,\"sort\":1},{\"id\":1015,\"name\":\"Acne Studios\",\"initialId\":10017,\"initialCode\":\"A\",\"consumerId\":102,\"sort\":2}]},{\"name\":\"B\",\"consumerId\":102,\"sort\":2,\"brandList\":[{\"id\":1012,\"name\":\"BALLY\",\"initialId\":10018,\"initialCode\":\"B\",\"consumerId\":102,\"sort\":1}]}]}]";
        String collectJson="[{\"name\":\"AEG\"},{\"name\":\"BALLY\"}]";
        BrandCategoryPO brandCategoryPO = parseJson(consumerId, collection, brandCategoryJson, collectJson);
        ObjectMapper mapper = new ObjectMapper();
        try {
            String json = mapper.writeValueAsString(brandCategoryPO);
            System.out.println();
            System.out.println(json);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }


    public String buildBrandJson(){
        Map<String, Object> consumerParams = new HashMap<>();
        Map<String, Object> initialParams;
        Map<String, Object> brandParams;
        List<TConsumerEntity> consumerListAll = consumerService.selectList(consumerParams);
        List<TInitialEntity> initialListNew;
        //品牌列表不为空的 品类集合
        Map<Long,List<TInitialEntity>> initialMap = new HashMap<>();
        //消费者分类：男士，女士
        for(TConsumerEntity consumer: consumerListAll){
            initialListNew = new ArrayList<>();
            initialParams = new HashMap<>();
            initialParams.put("consumerId",consumer.getId());
            List<TInitialEntity> initialList = initialService.selectList(initialParams);
            //首字母
            for(TInitialEntity intiial : initialList){
                brandParams = new HashMap<>();
                brandParams.put("initialId",intiial.getId());
                List<TBrandEntity> brandList = brandService.selectList(brandParams);
                if(CollectionUtils.isEmpty(brandList)){
                    continue;
                }
                intiial.setBrandList(brandList);
                if(intiial.getConsumerId().equals(consumer.getId()) && CollectionUtils.isNotEmpty(brandList)){
                    initialListNew.add(intiial);
                }
            }
            initialMap.put(consumer.getId(),initialListNew);
        }
        //重新构建
        for(TConsumerEntity consumer: consumerListAll){
            consumer.setInitialList(initialMap.get(consumer.getId()));
        }
        ObjectMapper mapper = new ObjectMapper();
        String json="";
        try {
            json = mapper.writeValueAsString(consumerListAll);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return json;
    }


    /**
     * 解析 json
     */
    public BrandCategoryPO parseJson(Long consumerId, Boolean collection, String brandJson, String collectJson){
        List<BrandVO> collectList = JSON.parseArray(collectJson, BrandVO.class);
        Set<String> collectSet = getCollectionSet(collectList);
        List<ConsumerPO> consumerList = JSON.parseArray(brandJson, ConsumerPO.class);
        //新的分类，过滤只看收藏的内容
        Map<Long,List<InitialPO>> initialMap = new HashMap<>();
        //收藏的集合
        List<InitialPO> initialCollectionList;
        List<InitialPO> initialPOList = new ArrayList<>();
        List<BrandPO> brandCollectionVOList = null;
        InitialPO initialCollectionVO =null;
        for(ConsumerPO consumer : consumerList){
            if(!consumerId.equals(consumer.getId())){
                continue;
            }
            initialCollectionList = new ArrayList<>();
            List<InitialPO> initials = consumer.getInitialList();
            for(InitialPO initial : initials){
                if(!initial.getConsumerId().equals(consumerId)){
                    continue;
                }
                //只看收藏的时候，不返回热门品牌分类
                if(collection && initial.getName().contains("热门")){
                    continue;
                }

                brandCollectionVOList = new ArrayList<>();
                //遍历，收藏标识 赋值
                for(BrandPO brandPO:initial.getBrandList()){
                    boolean isCollection =collectSet.contains(brandPO.getName());
                    brandPO.setCollection(isCollection);
                    if(collection && isCollection){
                        brandCollectionVOList.add(brandPO);
                    }
                }
                if(collection && CollectionUtils.isNotEmpty(brandCollectionVOList)){
                    initialCollectionVO = new InitialPO();
                    initialCollectionVO.setName(initial.getName());
                    initialCollectionVO.setBrandList(brandCollectionVOList);
                    initialCollectionVO.setSort(initial.getSort());
                    initialCollectionList.add(initialCollectionVO);
                }else{
                    initialPOList.add(initial);
                }
            }
            if(collection){
                //收藏的 数据
                initialMap.put(consumer.getId(),initialCollectionList);
            }else{
                //全部 数据
                initialMap.put(consumer.getId(), initialPOList);
            }
        }
        List<InitialPO> respInitialList = new ArrayList<>();
        //重新构建
        for(ConsumerPO consumer : consumerList){
            if(!consumerId.equals(consumer.getId())){
                continue;
            }
            respInitialList.addAll(initialMap.get(consumer.getId()));
        }
        BrandCategoryPO brandCategoryPO = new BrandCategoryPO();
        brandCategoryPO.setBrands(respInitialList);
       return brandCategoryPO;
    }

    /**
     *收藏的集合转换为 set
     */
    private Set<String> getCollectionSet(List<BrandVO> brandVOList){
        if(CollectionUtils.isEmpty(brandVOList)){
            return new HashSet<>();
        }
        // 将 List<BrandVO> 中的 name 属性转换为 Set<String>
        Set<String> collectionSet = brandVOList.stream().map(BrandVO::getName).collect(Collectors.toSet());
        return collectionSet;
    }


}
